// pages/recharge/recharge.js

import { getMemberById, updateBalance } from '@/api/member'
import { hideLoading, msg, showLoading } from '@/utils/util'
import { wxpay } from '@/api/pay'

Page({

    data: {
        // 充值列表
        rechargeList: [
            {id: 1, payAmount: 0.01, rechargeAmount: 0.01},
            {id: 2, payAmount: 50, rechargeAmount: 60},
            {id: 3, payAmount: 100, rechargeAmount: 130},
            {id: 4, payAmount: 300, rechargeAmount: 400},
            {id: 5, payAmount: 500, rechargeAmount: 680},
            {id: 6, payAmount: 1000, rechargeAmount: 1400},
        ],
        selected: null, // 选中充值项
        balance: '0.00', // 会员当前余额
        member: null, // 当前会员
    },

    onLoad() {
        this.setData({ selected: this.data.rechargeList[0] })

        this.loadMemberData()
    },

    // 切换充值项
    changeRecharge(e) {
        // console.log('changeRecharge',e )
        const { selected } = e.currentTarget.dataset
        this.setData({ selected })
    },

    // 查询会员数据：余额
    async loadMemberData() {
        try {
            showLoading()
            // 获取登录会员信息，要求必须登录了true
            const {member, logined} = getApp().current(true)
            if (!logined) return
            // 查询会员
            const { data } = await getMemberById(member._id)
            console.log('data', data)
            // 10 >  10.00 转换为2位小数字符串
            const balance = data.balance ? parseFloat(data.balance).toFixed(2) : '0.00'
            this.setData({ balance, member: data })
        } catch (error) {
            msg('查询账户余额失败')
            console.error('查询账户余额失败', error)
        } finally {
            hideLoading()
        }
    },

    // 提交充值
    async submitRecharge() {
        try {
            showLoading('充值中')
            this.setData({loading: true})
            const {member, selected} = this.data
            // 1. 校验是否已选择充值项
            if (!selected || !selected.id) {
                msg('请选择充值金额', {icon: 'error'})
                return
            }

            const {payAmount, rechargeAmount} = selected
            // TODO 2. 发起微信支付请求
            const orderNo = "R" + Date.now()
            const payRes = await wxpay('账户充值', orderNo, payAmount, 'wxpayCallRecharge')
            console.log('支付结果', payRes)
            // 3. 支付成功：更新会员余额
            await updateBalance(member._id, rechargeAmount)
            // 4. 查询会员最新数据：最新余额数据
            await this.loadMemberData()
            msg('充值成功', {icon: 'success'})
        } catch (error) {
            console.error("充值失败：", error)
            msg('充值失败', {icon: 'error'})
        } finally {
            hideLoading()
            this.setData({loading: false})
        }
        
    }

})